package cn.bdqn.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.bdqn.bean.User;
import cn.bdqn.service.UserService;
import cn.bdqn.service.impl.UserServiceImpl;

public class UpdatePasswordServlet extends HttpServlet {

	/**
		 * The doGet method of the servlet. <br>
		 *
		 * This method is called when a form has its tag value method equals to get.
		 * 
		 * @param request the request send by the client to the server
		 * @param response the response send by the server to the client
		 * @throws ServletException if an error occurred
		 * @throws IOException if an error occurred
		 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		
	}

	/**
		 * The doPost method of the servlet. <br>
		 *
		 * This method is called when a form has its tag value method equals to post.
		 * 
		 * @param request the request send by the client to the server
		 * @param response the response send by the server to the client
		 * @throws ServletException if an error occurred
		 * @throws IOException if an error occurred
		 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		UserService userService = new UserServiceImpl();
		//获取页面上用户输入的信息
		String oldPassword = request.getParameter("oldPassword");
		String newPassword = request.getParameter("newPassword");
		String reNewPassword = request.getParameter("reNewPassword");
		
		//获取当前在线用户的信息
		
		Object obj = request.getSession().getAttribute("user");
		if(obj==null){
			//去登录页面
			response.sendRedirect("jsp/login.jsp");
		}else{
			User user = (User) obj;
			if(user.getPassword().equals(oldPassword)){
				//原始密码输入正确
				//两次输入的新密码一致，可以修改新密码
				if(newPassword.equals(reNewPassword)){
					user.setPassword(newPassword);
					if(userService.updateUser(user)){
						//修改成功后重新登录
						response.sendRedirect("LogoutServlet");
					}else{
						response.sendRedirect("jsp/password.jsp");
					}
					
				}else{
					//两次输入的新密码不一致
					response.sendRedirect("jsp/password.jsp");
				}
			}else{
				//原始密码输入不正确
				/*request.setAttribute("msg", "原始密码输入不正确！");*/
				response.sendRedirect("jsp/password.jsp");
			}
		}
	}

}
